import React, {
    Component,
} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Platform,
    Dimensions,
    TouchableOpacity,
    Image,
    Alert,
    FlatList,
    TextInput,
    Linking,
    ScrollView,
    Switch,
    DeviceEventEmitter,
    PermissionsAndroid
} from 'react-native';

import moment from 'moment';
import HttpUtils from '../../utils/HttpUtils';
import HttpUrls from '../../utils/HttpUrls';
import AndroidModule from "../../utils/AndroidConnent";
import { ToastToUser } from "../../utils/CustomToast";
import Constant from '../../utils/Constant'
import NoData from '../../utils/NoData'
import Header from "../../components/header";
import { getImgUrl } from '../../utils/ComFunction'
import Loading from "../../utils/Loading";
import CommonAlertView from "../common/CommonAlertView";
import Picker from 'react-native-picker'
import ActionSheet from 'react-native-actionsheet'
import Upload from '../../components/upload/Upload'
import ImageCropPicker from 'react-native-image-crop-picker';
import { requestCameraPermission } from '../../utils/Permission';
import { StackActions } from '@react-navigation/native';
import PermissionDialog from "../../components/dialog/PermissionDialog";

const isIos = Platform.OS == 'ios';

const screenW = Dimensions.get('window').width;
let navigation

export default class CompanyEmployeeEdit extends Component {
    constructor(props) {
        super(props);
        let isAdd = this.props.route && this.props.route.params ? this.props.route.params.isAdd : false
        let employee = this.props.route && this.props.route.params && this.props.route.params.employee ? JSON.parse(this.props.route.params.employee) : { staffStatus: 1 }
        this.state = {
            isAdd: isAdd,
            employee: employee,
            userId: employee && employee.userId ? employee.userId : '',
            face: employee && employee.face ? employee.face : '',
            fullname: employee ? employee.fullname : '',
            userPhone: employee ? employee.userPhone : '',
            roleName: employee ? employee.job : '',
            roleId: employee ? employee.roleId : '',
            staffStatus: employee.staffStatus == 1 ? 1 : 0,
            staffStatusValue: [employee.staffStatus == 1 ? '正常' : '已离职'],
            remark: employee && employee.remark ? employee.remark : '',
            isUnionContact: employee && employee.isUnionContact ? true : false,
            switchcolor: {
                false: '#e4e4e4',
                true: '#30bf47',
            },
            remarkMaxLength: 500,
            introPop: false,
            showAlertView: false,
            dialogVisible: false
        }
    }

    componentDidMount() {

    }

    componentWillUnmount() {
        Picker.hide();
    }

    render() {
        navigation = this.props.navigation;
        return (
            <View style={styles.container}>
                <Header navigation={navigation} Title={this.state.isAdd ? '添加员工' : '编辑员工'} RightButton={() => this.renderRightButton()}></Header>

                <ScrollView style={{ flex: 1 }} showsVerticalScrollIndicator={false}>
                    <TouchableOpacity
                        style={styles.headBox}
                        activeOpacity={0.8}
                        onPress={() => {
                            this.ActionSheet.show()
                        }}
                    >
                        {
                            this.state.face ?
                                <Image style={styles.headImg} source={{ uri: getImgUrl(this.state.face) }} />
                                :
                                <Image style={styles.headImg} source={require('source/image/userIcon.png')} />

                        }
                        <Image source={require('source/image/comm/icon_tree_arrow.png')} style={styles.arrowImg} />
                    </TouchableOpacity>
                    <View style={styles.sepLine} />
                    <View style={styles.infoBox}>
                        <View style={styles.baseBox}>
                            <Text style={{ color: '#333', fontSize: 16, fontWeight: '500' }}>基本信息</Text>
                        </View>
                        <View style={styles.itemBox}>
                            <View style={styles.itemLeftBox}>
                                <Text style={styles.itemTitleText}>员工名称</Text>
                                <Text style={styles.itemNecessaryText}>*</Text>
                            </View>
                            <TextInput
                                clearButtonMode='while-editing'
                                style={styles.textInput}
                                placeholder='请输入员工名称'
                                returnKeyType='done'
                                value={this.state.fullname}
                                onChangeText={this.onChangeNameTextHandle}
                            />
                        </View>
                        <View style={styles.itemBox}>
                            <View style={styles.itemLeftBox}>
                                <Text style={styles.itemTitleText}>联系电话</Text>
                                <Text style={styles.itemNecessaryText}>*</Text>
                            </View>
                            <TextInput
                                clearButtonMode='while-editing'
                                style={styles.textInput}
                                placeholder='请输入联系电话'
                                maxLength={11}
                                keyboardType='number-pad'
                                value={this.state.userPhone}
                                onChangeText={this.onChangePhoneTextHandle}
                            />
                        </View>
                        <View style={styles.itemBox}>
                            <View style={styles.itemLeftBox}>
                                <Text style={styles.itemTitleText}>职务</Text>
                                <Text style={styles.itemNecessaryText}>*</Text>
                            </View>
                            <TouchableOpacity
                                style={styles.arrowBg}
                                activeOpacity={0.8}
                                onPress={() => {
                                    navigation.navigate('CompanyDutyList', {
                                        selectRoleId: this.state.roleId,
                                        completion: (item) => {
                                            this.setState({
                                                roleName: item.roleName,
                                                roleId: item.roleId
                                            })
                                            navigation.goBack()
                                        }
                                    })
                                }}
                            >
                                <Text style={styles.itemTitleText}>{this.state.roleName}</Text>
                                <Image source={require('source/image/comm/icon_tree_arrow.png')} style={styles.arrowImg} />
                            </TouchableOpacity>
                        </View>
                        <View style={styles.itemBox}>
                            <View style={styles.itemLeftBox}>
                                <Text style={styles.itemTitleText}>状态</Text>
                                <Text style={styles.itemNecessaryText}>*</Text>
                            </View>
                            <TouchableOpacity
                                style={styles.arrowBg}
                                activeOpacity={0.8}
                                onPress={() => {
                                    this.showStatusPicker()
                                }}
                            >
                                <Text style={styles.itemTitleText}>{this.state.staffStatus == '1' ? '正常' : '已离职'}</Text>
                                <Image source={require('source/image/comm/icon_tree_arrow.png')} style={styles.arrowImg} />
                            </TouchableOpacity>
                        </View>
                        <View style={[styles.itemBox, { justifyContent: 'space-between', borderBottomWidth: 0 }]}>
                            <View style={[styles.itemLeftBox, { width: 100 }]}>
                                <Text style={styles.itemTitleText}>指定联系人</Text>
                                <TouchableOpacity
                                    style={{ width: 30, height: 40, justifyContent: 'center', alignItems: 'center' }}
                                    onPress={() => {
                                        this.showPop()
                                    }}
                                >
                                    <Image style={{ width: 11, height: 11 }} source={require('source/image/icon_ask_gray.png')} />
                                </TouchableOpacity>
                            </View>

                            <Switch
                                disabled={this.state.staffStatus != '1' ? true : false}
                                style={{ transform: [{ scaleX: 1.0 }, { scaleY: 1.0 }] }}
                                value={this.state.staffStatus == 1 ? this.state.isUnionContact : false}
                                trackColor={this.state.switchcolor}
                                thumbColor='white'
                                onValueChange={(value) => {
                                    this.valueChanged();
                                }}
                            >
                            </Switch>

                        </View>
                    </View>
                    <View style={styles.sepLine} />
                    <View style={[styles.infoBox, { paddingTop: 0 }]}>
                        <View style={styles.remarkBox}>
                            <Text style={styles.itemTitleText}>备注</Text>
                            <View style={styles.remarkBg}>
                                <TextInput
                                    clearButtonMode='while-editing'
                                    maxLength={this.state.remarkMaxLength}
                                    style={styles.remarkTextInput}
                                    placeholder='请输入备注内容'
                                    multiline={true}
                                    placeholderTextColor="#B2B2B2"
                                    value={this.state.remark}
                                    lineHeight={20}
                                    onChangeText={this.onChangeRemarkTextHandle}
                                />
                                <Text style={styles.remarkCountText}>{this.state.remark.length + '/' + this.state.remarkMaxLength}</Text>
                            </View>

                        </View>
                    </View>

                    {
                        this.state.introPop ?
                            <View style={styles.introPopBg}>
                                <View style={{ width: '100%', height: 40, backgroundColor: 'rgba(0,0,0,0.5)', borderRadius: 4, paddingLeft: 8, paddingTop: 5, }}>
                                    <Text style={styles.introText}>联盟车商将直接联系指定员工,您有三个设置名额</Text>
                                </View>
                                <View style={[styles.triangle]} />
                            </View>
                            :
                            null
                    }

                </ScrollView>

                <View style={[styles.deleteBg, { height: Constant.bottomHeight + 50 }]}>
                    <TouchableOpacity
                        style={styles.deleteBox}
                        onPress={() => {
                            this.save()
                        }}
                    >
                        <Text style={styles.deleteText}>保存</Text>
                    </TouchableOpacity>
                </View>

                <ActionSheet
                    ref={o => this.ActionSheet = o}
                    title={'请选择照片来源 ?'}
                    options={['相册', '拍照', '取消']}
                    cancelButtonIndex={2}
                    onPress={(index) => { this.selectPhoto(index) }}
                />

                {
                    this.state.showAlertView ?
                        <CommonAlertView
                            title={'温馨提示'}
                            notice={'您添加的员工数量已到达上限，如有需要请联系客服人员。'}
                            sureDes={'联系客服'}
                            cancelDes={'取消'}
                            sureAction={() => {
                                this.setState({
                                    showAlertView: false,
                                }, function () {
                                    this.call()
                                })
                            }}
                            cancelAction={() => {
                                this.setState({
                                    showAlertView: false,
                                })
                            }}
                        />
                        : null
                }

                <PermissionDialog
                    visible={this.state.dialogVisible}
                    onClose={() => this.setDialogVisible(false)}
                    title={'申请相机拍照权限和文件读写存储权限'}
                    content={'申请相机拍照权限，用于完成个人头像拍照;申请文件读写权限，用于完成拍照后的图片裁剪保存，完成头像上传'}
                    permissions={[
                        PermissionsAndroid.PERMISSIONS.CAMERA,
                        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE
                    ]}
                />

                <Loading onRef={(ref) => (this.Loading = ref)} />
            </View>
        )
    }

    renderRightButton() {
        if (this.state.isAdd) {
            return (
                null
            )
        }
        return (
            <TouchableOpacity
                activeOpacity={0.8}
                onPress={() => { this.deleteStaff() }}>
                <View style={styles.rightBox}>
                    <Text style={styles.rightText}>删除员工</Text>
                </View>
            </TouchableOpacity>
        )
    }

    save() {
        if (!this.state.fullname) {
            ToastToUser('请填写员工名称')
            return
        }
        if (this.state.fullname.length > 10) {
            ToastToUser('员工名称字符个数不能大于10')
        }
        if (!this.state.userPhone) {
            ToastToUser('请填写联系电话')
            return
        }
        if (this.state.userPhone.length != 11) {
            ToastToUser('请输入正确的11位手机号')
            return
        }
        if (!this.state.roleId) {
            ToastToUser('请选择职务')
            return
        }

        if (this.state.isAdd) {
            this.Loading.show('添加员工中...');
        } else {
            this.Loading.show('保存中...');
        }

        let params = {
            face: this.state.face,
            fullname: this.state.fullname,
            isUnionContact: this.state.isUnionContact ? 1 : 0,
            merchantId: Constant.userInfo.merchantId,
            phone: this.state.userPhone,
            remark: this.state.remark,
            roleId: this.state.roleId,
            roleName: this.state.roleName,
            staffStatus: this.state.staffStatus,
            userId: this.state.userId
        }

        HttpUtils.postRequest(this.state.isAdd ? HttpUrls.addStaff : HttpUrls.updateStaff, params)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
                if (result.code == 0) {
                    let employee = this.state.employee
                    employee.face = this.state.face
                    employee.fullname = this.state.fullname
                    employee.isUnionContact = this.state.isUnionContact
                    employee.userPhone = this.state.userPhone
                    employee.remark = this.state.remark
                    employee.roleId = this.state.roleId
                    employee.job = this.state.roleName
                    employee.staffStatus = this.state.staffStatus
                    employee.userId = this.state.userId
                    this.setState({
                        employee: employee
                    }, function () {
                        if (this.props.route.params && this.props.route.params.completion) {
                            this.props.route.params.completion(this.state.employee)
                        }
                        navigation.goBack()
                    })
                } else if (result.code + '' == '-2010819') {
                    this.setState({
                        showAlertView: true
                    })
                } else {
                    ToastToUser(result.msg)
                }
            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
            });
    }

    deleteStaff() {
        Alert.alert('删除员工', '是否确认删除此员工?',
            [{ text: "取消" },
            {
                text: "确定", onPress: () => {
                    let param = {
                        merchantId: Constant.userInfo.merchantId,
                        userId: this.state.userId
                    }
                    this.Loading.show('删除中...')
                    HttpUtils.getRequest(HttpUrls.deleteStaff, param)
                        .then((result) => {
                            this.Loading.hide()
                            if (result.code == 0) {
                                DeviceEventEmitter.emit('deleteStaffSuccess', { userId: this.state.userId });
                                navigation.dispatch(StackActions.pop(2));
                            } else {
                                ToastToUser(result.msg)
                            }
                        })
                        .catch((error) => {
                            this.Loading.hide()
                        });
                }
            }]
        )
    }

    call() {
        let param = {
            key: 'shuaicheTelephone',
        }
        HttpUtils.getRequest(HttpUrls.configProperties, param)
            .then((result) => {
                let data = result.data
                if (data) {
                    const url = `tel:${data.shuaicheTelephone}`;
                    Linking.canOpenURL(url).then(supported => {
                        if (!supported) {
                            return Alert.alert('提示', `您的设备不支持该功能，请手动拨打 ${data.shuaicheTelephone}`, [
                                { text: '确定' }
                            ]);
                        }
                        return Linking.openURL(url);
                    }).catch(err => Alert(err));
                }
            })
            .catch((error) => {

            });
    }

    showPop() {
        this.setState({
            introPop: true
        }, function () {
            setTimeout(() => {
                this.setState({
                    introPop: false
                })
            }, 3000);
        })
    }

    onChangeNameTextHandle = (value) => {
        this.setState({
            fullname: value
        })
    }

    onChangePhoneTextHandle = (value) => {
        this.setState({
            userPhone: value
        })
    }

    onChangeRemarkTextHandle = (value) => {
        this.setState({
            remark: value
        })
    }

    valueChanged() {
        if (this.state.isUnionContact) {
            this.setState({
                isUnionContact: false,
            });
        } else {
            this.setState({
                isUnionContact: true,
            }, function () {
                this.isUnionContact()
            });
        }
    }

    isUnionContact() {
        if (this.Loading) {
            this.Loading.show();
        }
        let param = {
            merchantId: Constant.userInfo.merchantId,
            userId: this.state.userId
        }
        HttpUtils.getRequest(HttpUrls.isUnionContact, param)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
                let data = result.data
                if (data != 1) {
                    ToastToUser('您最多只能指定三名联系人')
                    this.setState({
                        isUnionContact: false
                    })
                }
            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
            });
    }

    showStatusPicker() {
        let data = [
            '正常',
            '已离职',
        ];
        let datas = [
            { 'key': '1', 'value': '正常' },
            { 'key': '0', 'value': '已离职' },
        ];
        Picker.init({
            pickerData: data,
            selectedValue: this.state.staffStatusValue,
            // pickerBg:[255, 0 ,0, 1],
            pickerFontColor: [0, 0, 0, 1],
            pickerCancelBtnText: '取消',
            pickerCancelBtnColor: [134, 136, 137, 1],
            pickerConfirmBtnText: '确认',
            pickerTitleText: '',
            pickerToolBarBg: [255, 255, 255, 1],
            pickerBg: [255, 255, 255, 1],

            onPickerConfirm: data => {
                let value = '';
                for (var i = 0; i < datas.length; i++) {
                    if (datas[i].value == data) {
                        value = datas[i].key
                    }
                }
                this.setState({
                    staffStatusValue: data,
                    staffStatus: value
                })
            },
            onPickerCancel: data => {

            },
            onPickerSelect: data => {

            }
        });
        Picker.show();
    }

    //选择相册还是照相机
    selectPhoto(index) {
        if (index == 0) {
            //相册
            const option = {
                mediaType: "photo",
                cropping: false,
                compressImageQuality: .5,
                multiple: false,
            };
            ImageCropPicker.openPicker(option).then(images => {
                if (this.Loading) {
                    this.Loading.show();
                }
                Upload.getAlipz(images.path, Upload.OSS_FACE, this.uploadafterfun);//获取阿里凭证。

            }, (error) => {
                // alert(error);
            });

        } else if (index == 1) {
            //照相机
            this.openCamera();
        }
    }

    openCamera() {
        if (isIos) {
            this.takePhoto()
        } else {
            PermissionsAndroid.check('android.permission.CAMERA').then(res => {
                if (!res) {

                    this.setDialogVisible(true)
                }
                else {
                    this.takePhoto()
                }
            })
        }
    }

    setDialogVisible(dialogVisible) {
        this.setState({
            dialogVisible: dialogVisible
        })
    }

    takePhoto() {
        const option = { mediaType: "photo", cropping: false, compressImageQuality: .6, compressImageMaxWidth: 1024, compressImageMaxHeight: 1024 };
        ImageCropPicker.openCamera(option).then(images => {
            if (this.Loading) {
                this.Loading.show()
            }
            Upload.getAlipz(images.path, Upload.OSS_FACE, this.uploadafterfun);//获取阿里凭证。

        }, (error) => {
            // alert(error);
        });
    }

    // 上传图片成功后 回调
    uploadafterfun = (picUrl) => {
        if (this.Loading) {
            this.Loading.hide();
        }
        this.setState({
            face: picUrl
        })
    }


}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F9F9F9',
    },
    rightBox: {
        height: '100%',
        width: 70,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'flex-end',
    },
    rightText: {
        fontSize: 16,
        color: '#333333',
        fontWeight: 'bold',
    },
    headBox: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        height: 82,
        backgroundColor: '#fff',
        paddingHorizontal: 12,
    },
    headImg: {
        width: 56,
        height: 56,
        borderRadius: 28,
    },
    arrowImg: {
        width: 16,
        height: 16
    },
    sepLine: {
        width: '100%',
        height: 10
    },
    infoBox: {
        flexDirection: 'column',
        justifyContent: 'flex-start',
        alignItems: 'flex-start',
        backgroundColor: '#fff',
        paddingLeft: 12,
        paddingTop: 60,
    },
    baseBox: {
        position: 'absolute',
        top: 12,
        left: 0,
        width: 100,
        height: 36,
        marginBottom: 12,
        justifyContent: 'center',
        alignItems: 'center',
        borderBottomRightRadius: 18,
        borderTopRightRadius: 18,
        backgroundColor: '#ffde00'
    },
    itemBox: {
        width: '100%',
        paddingRight: 12,
        height: 45,
        flexDirection: 'row',
        justifyContent: 'flex-start',
        alignItems: 'center',
        backgroundColor: '#fff',
        borderBottomColor: '#e4e4e4',
        borderBottomWidth: 0.3,
    },
    itemLeftBox: {
        flexDirection: 'row',
        alignItems: 'center',
        width: 68
    },
    textInput: {
        marginLeft: 25,
        flex: 1,
        height: '100%'
    },
    arrowBg: {
        marginLeft: 25,
        flex: 1,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between'
    },
    itemTitleText: {
        fontSize: 14,
        color: '#333',
    },
    itemNecessaryText: {
        marginLeft: 5,
        color: 'red'
    },
    remarkBox: {
        flexDirection: 'column',
        width: '100%',
        paddingRight: 12,
        paddingTop: 14,
        paddingBottom: 14,
        backgroundColor: '#fff',
    },
    remarkText: {
        fontSize: 14,
        color: '#999',
        lineHeight: 18
    },
    remarkBg: {
        marginTop: 15,
        width: '100%',
        height: 120,
        borderRadius: 4,
        backgroundColor: '#F7F7F7'
    },
    remarkTextInput: {
        padding: 12,
        flex: 1,
        height: '100%',
        textAlignVertical: 'top'
    },
    remarkCountText: {
        position: 'absolute',
        right: 12,
        bottom: 12,
        color: '#333',
        fontSize: 13
    },
    introPopBg: {
        position: 'absolute',
        left: 110,
        top: 290,
        width: 200,
        height: 60,
        flexDirection: 'column',
    },
    triangle: {
        marginLeft: 10,
        width: 0,
        height: 0,
        backgroundColor: 'transparent',
        borderStyle: 'solid',
        borderLeftWidth: 6,
        borderRightWidth: 6,
        borderBottomWidth: 0,
        borderTopWidth: 10,
        borderLeftColor: 'transparent',
        borderRightColor: 'transparent',
        borderTopColor: 'rgba(0,0,0,0.5)'
    },
    introText: {
        color: '#fff',
        fontSize: 12,
    },
    deleteBg: {
        width: '100%',
        paddingHorizontal: 15,
    },
    deleteBox: {
        marginTop: 5,
        width: '100%',
        height: 40,
        backgroundColor: '#FFE000',
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: 4
    },
    deleteText: {
        color: '#333333',
        fontSize: 15
    }

})